// Get DOM elements
const fileInput = document.getElementById('fileInput');
const selectedFilesInfoDiv = document.getElementById('selectedFilesInfo');
// const outputFormatSelect = document.getElementById('outputFormat'); // Removed
const compressButton = document.getElementById('compressButton');
const statusDiv = document.getElementById('status');
const resultsDiv = document.getElementById('results');
const resultListDiv = document.getElementById('result-list');

// Removed outputFormats object and populateFormats function

// --- Update selected file info when file input changes ---
fileInput.addEventListener('change', () => {
    const files = fileInput.files;
    if (files && files.length > 0) {
        let fileNames = [];
        for (let i = 0; i < files.length; i++) {
            fileNames.push(files[i].name);
        }
        selectedFilesInfoDiv.textContent = `已选择: ${fileNames.join(', ')}`;
        selectedFilesInfoDiv.style.display = 'block'; // Show the info area
    } else {
        selectedFilesInfoDiv.textContent = ''; // Clear info
        selectedFilesInfoDiv.style.display = 'none'; // Hide the info area
    }
});

// Function to update status display
function updateStatus(message, type = 'info') { // type can be 'info', 'processing', 'success', 'error'
    statusDiv.textContent = message;
    statusDiv.className = ''; // Remove previous classes
    if (type !== 'info') {
        statusDiv.classList.add(type);
    }
}

// Function to display results
function displayResults(resultsData) {
    resultListDiv.innerHTML = ''; // Clear previous results
    if (!resultsData || resultsData.length === 0) {
        resultsDiv.style.display = 'none';
        return;
    }

    resultsData.forEach(item => {
        const resultItem = document.createElement('div');
        resultItem.classList.add('result-item');

        const detailsDiv = document.createElement('div');
        detailsDiv.classList.add('result-details');

        const fileNameSpan = document.createElement('span');
        fileNameSpan.classList.add('file-name');
        // Use the actual output filename received from the backend
        fileNameSpan.textContent = item.outputFilename; // Changed from item.originalFilename
        detailsDiv.appendChild(fileNameSpan);

        const statusSpan = document.createElement('span');
        statusSpan.classList.add('status-text');
        if (item.status === 'SUCCESS') {
            statusSpan.classList.add('status-success');
            statusSpan.textContent = `状态: 成功`;
            const sizeSpan = document.createElement('span');
            sizeSpan.classList.add('final-size');
            sizeSpan.textContent = `大小: ${item.finalSize}`;
            detailsDiv.appendChild(statusSpan);
            detailsDiv.appendChild(sizeSpan);

             // Add download link only on success
            const downloadLink = document.createElement('a');
            downloadLink.classList.add('download-link');
            // Construct download URL based on the filename returned from backend
            downloadLink.href = `/api/images/download/${encodeURIComponent(item.outputFilename)}`;
            downloadLink.textContent = '下载';
            // downloadLink.target = '_blank'; // Optional: open in new tab
            resultItem.appendChild(downloadLink);

        } else { // FAILURE
            statusSpan.classList.add('status-failure');
            statusSpan.textContent = `状态: 失败`;
            const errorSpan = document.createElement('span');
            errorSpan.classList.add('error-message');
            errorSpan.textContent = `错误: ${item.errorMessage || '未知错误'}`;
            detailsDiv.appendChild(statusSpan);
            detailsDiv.appendChild(errorSpan);
        }

        resultItem.insertBefore(detailsDiv, resultItem.firstChild); // Add details to the start
        resultListDiv.appendChild(resultItem);
    });

    resultsDiv.style.display = 'block'; // Show results container
}

// Handle compress button click
compressButton.addEventListener('click', async () => {
    const files = fileInput.files;
    // const selectedFormat = outputFormatSelect.value; // Removed
    const outputFormat = 'JPEG'; // Hardcoded as JPEG is the only option

    if (!files || files.length === 0) {
        updateStatus('请先选择要压缩的文件。', 'error');
        return;
    }

    compressButton.disabled = true;
    updateStatus(`正在处理 ${files.length} 个文件...`, 'processing');
    resultsDiv.style.display = 'none';
    resultListDiv.innerHTML = '';

    const formData = new FormData();
    for (let i = 0; i < files.length; i++) {
        formData.append('files', files[i]);
    }
    formData.append('outputFormat', outputFormat); // Use the hardcoded format

    try {
        const response = await fetch('/api/images/upload', {
            method: 'POST',
            body: formData,
        });

        if (!response.ok) {
             let errorMsg = `HTTP 错误: ${response.status} ${response.statusText}`;
             try {
                 const errorBody = await response.text();
                 errorMsg = errorBody || errorMsg;
             } catch (e) { /* Ignore */ }
             throw new Error(errorMsg);
        }

        const resultsData = await response.json();
        displayResults(resultsData);
        updateStatus(`处理完成 ${resultsData.length} 个文件。`, 'success');

    } catch (error) {
        console.error('压缩请求失败:', error);
        updateStatus(`发生错误: ${error.message}`, 'error');
        resultsDiv.style.display = 'none';
    } finally {
        compressButton.disabled = false;
        // fileInput.value = null; // Don't clear immediately, user might want to see selected files
        // We can clear the file info display instead, or leave it
        // selectedFilesInfoDiv.textContent = '';
        // selectedFilesInfoDiv.style.display = 'none';
    }
});

// Initial setup - removed call to populateFormats
document.addEventListener('DOMContentLoaded', () => {
    // No format population needed anymore
}); 